def grid(cols, rows, colsize = 1, rowsize = 1, &block)
  block = Proc.new {|*args| args} unless block
  (0 ... cols * rows).map do |i|
    x = colsize * (i % cols)
    y = rowsize * i.div(cols)
    block.call(x, y)
  end
end


Array.module_eval do
  def choice
    self[rand(length)]
  end
end



class Motion
  require 'rplib.jar'
  include_class 'IPAppletAdapter'
  include IPAppletAdapter
  
  attr :frame
  attr :progress

  def initialize(frames = nil, &block)
    super()
    @frame = 0
    @progress = 0
    @running = false
    each_frame(frames, &block) if block
  end
  
  def start
    @frame = 0
    @progress = 0
    unless @running
      @running = true
      $irp.applet.registerDraw(self)
    end
    self
  end
  
  def draw
    @frame += 1
    @progress = @frame / @frames.to_f if @frames
    @each_frame.call(self)
    stop if @frame >= @frames if @frames
  end
  
  def stop
    if @running
      @running = false
      $irp.applet.unregisterDraw(self)
    end
    self
  end
  
  def running?
    @running
  end
  
  def each_frame(frames, &block)
    @frames = frames
    @each_frame = block
    start
  end
end